import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TimeZone;

public class HttpServer{
	final static String START = "Welcome to the Number Guess Game. Guess a number between 1 and 100.<br>";
	final static String HIGHER = "Nope, guess higher<br>";
	final static String LOWER = "Nope, guess lower<br>";
	final static String RESET = "New game started";


	static int lastclientID = 0;

	public static void main(String[] args) throws IOException{
		ArrayList<Client> clientlist = new ArrayList<Client>();
		System.out.println("Skapar Serversocket");
		ServerSocket ss = new ServerSocket(8080);
		while(true){
			int clientID = -1;

			System.out.println("Väntar på klient...");
			Socket s = ss.accept();
			System.out.println("Klient är ansluten");
			BufferedReader request =
					new BufferedReader(new InputStreamReader(s.getInputStream()));
			String str = request.readLine();
			StringTokenizer tokens =
					new StringTokenizer(str," ?");
			tokens.nextToken(); // Ordet GET
			String requestedDocument = tokens.nextToken();
			String cookiecmp = "Cookie: ";
			while( (str = request.readLine()) != null && str.length() > 0){
				if(str.startsWith(cookiecmp)){
						clientID = Integer.parseInt(str.split("=")[1]);
				}
				System.out.println(str);
			}
			String gt = tokens.nextToken();
			String gscmp = "guess=";
			Integer guess = null;
			if(gt.startsWith(gscmp)){
				guess = Integer.parseInt(gt.substring(gscmp.length()));
			}

			System.out.println("Förfrågan klar.");
			s.shutdownInput();

			PrintStream response =
					new PrintStream(s.getOutputStream());
			response.println("HTTP/1.1 200 OK");
			response.println("Server : Guessing Game");
			
			Client client = null;
			for(Client c : clientlist){
				if(c.getClientID() == clientID){
					client = c;
				}
			}
			if(client==null){
				//No expiration date means that cookie expires on session close
				response.println("Set-Cookie: clientId="+getNextClientID()+";");
				client = new Client(lastclientID, 0);
				clientlist.add(client);
			}
			System.out.println("GUESS: " + guess);
			if(guess != null){
				client.addGuess();
			}

			response.println();
			response.print(getPage(client, guess));

			s.shutdownOutput();
			s.close();

		}
	}

	private static int getNextClientID() {
		lastclientID++;
		return lastclientID;
	}

	private static String getPage(Client client, Integer guess){
		String head = "<html>\n" +
				"<head><title>Number Guess Game</title>\n"+
				"<script type = \"text/javascript\">\n" +
				"function inputfocus(form){\n" +
				"form.guess.focus()\n" +
				"}\n" +
				"</script>\n" +
				"</head>\n\n";

		String body  = "<body onLoad=\"inputfocus(document.guessform);\">\n" + 
				"<form name=\"guessform\">\n" +
				"<input type=text name=guess>\n" +
				"<input type=submit value=\"Guess\">\n" +
				"</form>\n\n" +
				"</body></html>\n";

		String guesses = "You have made " + client.noOfGuesses + " guess(es)<br>";

		if(client.noOfGuesses == 0){
			return head + START + body;
		}
		if(guess == null){
			return head + guesses + body;
		}
		if(client.answer == guess){
			String retur =  head + "You made it!!! <br>" + guesses + RESET + body;
			client.resetAnswer();
			return retur;
		}

		if(client.answer > guess){
			return head + HIGHER+ guesses + body;
		}
		if(client.answer < guess){
			return head + LOWER+ guesses + body;
		}
		return head + "somthing wrong" + body;
	}


}
